import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/buy_record_controller.dart';

class AddBuyRecordPage extends StatefulWidget {
  const AddBuyRecordPage({super.key});

  @override
  _AddBuyRecordPageState createState() => _AddBuyRecordPageState();
}

class _AddBuyRecordPageState extends State<AddBuyRecordPage> {
  final BuyRecordController _controller = Get.find();
  final _formKey = GlobalKey<FormState>();

  final _symbolController = TextEditingController();
  final _nameController = TextEditingController();
  final _priceController = TextEditingController();
  final _quantityController = TextEditingController();

  DateTime _selectedDate = DateTime.now();
  bool _isLoadingName = false;
  bool _hasSavedSuccessfully = false; // 新增：标记保存成功状态

  // 用于监听股票代码输入框的焦点变化
  final FocusNode _symbolFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _symbolController.addListener(_onSymbolChanged);

    // 添加焦点监听器
    _symbolFocusNode.addListener(_onSymbolFocusChange);

    // 如果有预填充的股票代码和名称
    final args = Get.arguments;
    if (args != null && args['symbol'] != null) {
      _symbolController.text = args['symbol'];
      _nameController.text = args['name'];
    }
  }

  @override
  void dispose() {
    _symbolController.removeListener(_onSymbolChanged);
    _symbolController.dispose();
    _nameController.dispose();
    _priceController.dispose();
    _quantityController.dispose();

    // 移除焦点监听器并释放资源
    _symbolFocusNode.removeListener(_onSymbolFocusChange);
    _symbolFocusNode.dispose();
    super.dispose();
  }

  // 监听股票代码输入框焦点变化
  void _onSymbolFocusChange() {
    if (!_symbolFocusNode.hasFocus) {
      // 失去焦点时自动添加前缀
      _autoAddPrefix();
    }
  }

  // 自动为股票代码添加前缀
  void _autoAddPrefix() {
    String symbol = _symbolController.text.trim();

    if (symbol.isEmpty) return;

    // 如果已经包含前缀，不做处理
    if (symbol.startsWith('sh') || symbol.startsWith('sz')) {
      return;
    }

    // 判断股票代码类型并添加相应前缀
    if (symbol.length >= 1) {
      String firstChar = symbol[0];

      // 6、5、9开头的股票通常是上海交易所
      if (['6', '5', '9'].contains(firstChar)) {
        _symbolController.text = 'sh$symbol';
      }
      // 0、2、3开头的股票通常是深圳交易所
      else if (['0', '2', '3'].contains(firstChar)) {
        _symbolController.text = 'sz$symbol';
      }
      // 其他情况，默认添加sh前缀
      else {
        _symbolController.text = 'sh$symbol';
      }
    }
  }

  // 根据股票代码获取带前缀的完整代码
  String _getFullSymbol(String symbol) {
    if (symbol.isEmpty) return symbol;

    // 如果已经包含前缀，直接返回
    if (symbol.startsWith('sh') || symbol.startsWith('sz')) {
      return symbol;
    }

    // 判断股票代码类型并添加相应前缀
    if (symbol.length >= 1) {
      String firstChar = symbol[0];

      // 6、5、9开头的股票通常是上海交易所
      if (['6', '5', '9'].contains(firstChar)) {
        return 'sh$symbol';
      }
      // 0、2、3开头的股票通常是深圳交易所
      else if (['0', '2', '3'].contains(firstChar)) {
        return 'sz$symbol';
      }
      // 其他情况，默认添加sh前缀
      else {
        return 'sh$symbol';
      }
    }

    return symbol;
  }

  void _onSymbolChanged() async {
    final symbol = _symbolController.text.trim();

    // 如果为空或长度不足，清除股票名称
    if (symbol.isEmpty || symbol.length < 4) {
      setState(() {
        _nameController.clear();
      });
      return;
    }

    // 获取带前缀的完整股票代码
    final fullSymbol = _getFullSymbol(symbol);

    if (_isValidStockSymbol(fullSymbol)) {
      setState(() {
        _isLoadingName = true;
      });

      try {
        final name = await _controller.getStockName(fullSymbol);

        if (mounted) {
          setState(() {
            _isLoadingName = false;
            if (name != null && name.isNotEmpty && name != "N/A") {
              _nameController.text = name;
            } else {
              _nameController.clear();
              // 如果查询失败但用户输入了完整的6位代码，显示提示
              if (symbol.length == 6 && RegExp(r'^\d{6}$').hasMatch(symbol)) {
                Get.snackbar(
                  '提示',
                  '未找到该股票，请检查代码是否正确',
                  snackPosition: SnackPosition.BOTTOM,
                  duration: const Duration(seconds: 3),
                );
              }
            }
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _isLoadingName = false;
            _nameController.clear();
          });
        }
      }
    } else {
      setState(() {
        _nameController.clear();
      });
    }
  }

  bool _isValidStockSymbol(String symbol) {
    // 允许不带前缀的6位数字代码
    final regexWithoutPrefix = RegExp(r'^\d{6}$');
    // 允许带前缀的8位代码
    final regexWithPrefix = RegExp(r'^(sh|sz)\d{6}$');
    return regexWithoutPrefix.hasMatch(symbol) || regexWithPrefix.hasMatch(symbol);
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  Future<void> _submitForm() async {
    // 在提交前确保股票代码有正确的前缀
    _autoAddPrefix();

    if (_formKey.currentState!.validate()) {
      final success = await _controller.addBuyRecord(
        symbol: _symbolController.text.trim(),
        name: _nameController.text.trim(),
        buyPrice: double.parse(_priceController.text),
        quantity: int.parse(_quantityController.text),
        buyDate: _selectedDate,
      );

      if (success) {
        // 显示成功提示
        Get.snackbar(
          '成功',
          '买入记录已保存',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green[100],
          colorText: Colors.green[900],
          duration: const Duration(seconds: 2),
        );

        // 设置保存成功标志，但不关闭页面
        setState(() {
          _hasSavedSuccessfully = true;
        });
      } else {
        // 显示失败提示
        Get.snackbar(
          '错误',
          '保存买入记录失败',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[900],
          duration: const Duration(seconds: 4),
        );
      }
    }
  }

  // 新增：关闭页面方法
  void _closePage() {
    // 返回保存成功状态，以便上级页面刷新
    Navigator.of(context).pop(_hasSavedSuccessfully);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // 拦截返回按钮，返回保存状态
        _closePage();
        return false; // 阻止默认返回行为
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('添加买入记录'),
          backgroundColor: Colors.blue[700],
          foregroundColor: Colors.white,
          leading: IconButton(
            icon: const Icon(Icons.close),
            onPressed: _closePage, // 使用关闭页面方法
          ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: SingleChildScrollView( // 添加滚动视图
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextFormField(
                    keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                    controller: _symbolController,
                    focusNode: _symbolFocusNode, // 添加焦点节点
                    decoration: const InputDecoration(
                      labelText: '股票代码*',
                      hintText: '例如: 601006 (自动添加sh/sz前缀)',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(Icons.tag),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入股票代码';
                      }
                      final symbol = value.trim();

                      // 检查是否已自动添加前缀
                      if (!symbol.startsWith('sh') && !symbol.startsWith('sz')) {
                        // 如果没有前缀，检查是否为6位数字
                        final regex = RegExp(r'^\d{6}$');
                        if (!regex.hasMatch(symbol)) {
                          return '请输入6位数字股票代码';
                        }
                      } else {
                        // 如果有前缀，检查格式是否正确
                        final regex = RegExp(r'^(sh|sz)\d{6}$');
                        if (!regex.hasMatch(symbol)) {
                          return '股票代码格式应为shXXXXXX或szXXXXXX';
                        }
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    controller: _nameController,
                    decoration: InputDecoration(
                      labelText: '股票名称*',
                      border: const OutlineInputBorder(),
                      prefixIcon: const Icon(Icons.text_fields),
                      suffixIcon: _isLoadingName
                          ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                          : null,
                    ),
                    readOnly: true, // 设置为只读，因为名称是自动获取的
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请先输入有效的股票代码';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    controller: _priceController,
                    decoration: const InputDecoration(
                      labelText: '买入价格*',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(Icons.attach_money),
                    ),
                    keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入买入价格';
                      }
                      final price = double.tryParse(value);
                      if (price == null || price <= 0) {
                        return '请输入有效的价格';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    controller: _quantityController,
                    decoration: const InputDecoration(
                      labelText: '买入数量*',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(Icons.format_list_numbered),
                    ),
                    keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入买入数量';
                      }
                      final quantity = int.tryParse(value);
                      if (quantity == null || quantity <= 0) {
                        return '请输入有效的数量';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  InkWell(
                    onTap: () => _selectDate(context),
                    child: InputDecorator(
                      decoration: const InputDecoration(
                        labelText: '买入日期*',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.calendar_today),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '${_selectedDate.year}-${_selectedDate.month.toString().padLeft(2, '0')}-${_selectedDate.day.toString().padLeft(2, '0')}',
                          ),
                          const Icon(Icons.calendar_today),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: _submitForm,
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      child: const Text('保存买入记录'),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}